<template>
  <div class="dish-manage">
    <el-card>
      <div class="card-header">
        <h2>菜品管理</h2>
        <div class="header-actions">
          <el-input
              v-model="searchName"
              placeholder="请输入菜品名称"
              style="width: 200px; margin-right: 10px;"
              clearable
              @keyup.enter="handleSearch"
          />
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button type="success" icon="Plus" @click="handleAdd">新增菜品</el-button>
          <el-button
              type="warning"
              icon="RefreshRight"
              @click="handleBatchStatus"
              :disabled="selectedIds.length === 0"
          >
            {{ batchStatusText }}
          </el-button>
          <el-button
              type="danger"
              icon="Delete"
              @click="handleBatchDelete"
              :disabled="selectedIds.length === 0"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 菜品列表表格 -->
      <el-table
          :data="dishList"
          border
          style="width: 100%"
          row-key="id"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="菜品名称" />
        <el-table-column prop="categoryName" label="所属分类" />
        <el-table-column prop="price" label="价格" :formatter="formatPrice" />
        <el-table-column prop="image" label="图片">
          <template #default="scope">
            <el-image
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                style="width: 50px; height: 50px; object-fit: cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启售' : '停售' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
                icon="Edit"
            >
              编辑
            </el-button>
            <el-button
                type="warning"
                size="small"
                @click="handleStatusChange(scope.row.id, scope.row.status === 1 ? 0 : 1)"
                icon="RefreshRight"
            >
              {{ scope.row.status === 1 ? '停售' : '启售' }}
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row.id)"
                icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination" style="margin-top: 15px; text-align: right;">
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名称" />
        </el-form-item>

        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="菜品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入菜品价格" type="number" />
        </el-form-item>

        <el-form-item label="菜品图片" prop="image">
          <el-upload
              action="/upload"
          :on-success="handleUploadSuccess"
          :show-file-list="false"
          accept="image/*"
          >
          <el-button type="primary">上传图片</el-button>
          </el-upload>
          <el-image
              v-if="form.image"
              :src="form.image"
              style="width: 100px; height: 100px; margin-top: 10px"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启售</el-radio>
            <el-radio :label="0">停售</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 口味信息（根据实际需求添加） -->
        <el-form-item label="菜品口味">
          <el-button type="text" @click="addFlavor">添加口味</el-button>
          <div v-for="(flavor, index) in form.flavors" :key="index" class="flavor-item">
            <el-input
                v-model="flavor.name"
                placeholder="口味名称"
                style="width: 150px; margin-right: 10px"
            />
            <el-input
                v-model="flavor.value"
                placeholder="口味值"
                style="width: 200px; margin-right: 10px"
            />
            <el-button type="text" @click="form.flavors.splice(index, 1)">删除</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  addDish,
  getDishPage,
  getDishById,
  updateDish,
  deleteDish,
  updateDishStatus
} from '../api/dish';
import { getCategories } from '../api/category';

// 表格数据
const dishList = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const searchName = ref('');
const selectedIds = ref([]);
const categoryList = ref([]);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('新增菜品');
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: null,
  name: '',
  categoryId: null,
  price: null,
  image: '',
  status: 1,
  flavors: [] // 口味列表
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 1, max: 32, message: '菜品名称长度在1-32个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择所属分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入菜品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传菜品图片', trigger: 'change' }
  ]
};

// 加载菜品列表
const loadDishList = async () => {
  try {
    const response = await getDishPage({
      page: page.value,
      pageSize: pageSize.value,
      name: searchName.value
    });
    if (response.code === 200) {
      dishList.value = response.data.records;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || '获取菜品列表失败');
    }
  } catch (error) {
    console.error('加载菜品失败:', error);
    ElMessage.error('获取菜品列表失败');
  }
};

// 加载分类列表
const loadCategoryList = async () => {
  try {
    const response = await getCategories();
    if (response.code === 200) {
      categoryList.value = response.data;
    }
  } catch (error) {
    console.error('加载分类失败:', error);
  }
};

// 搜索
const handleSearch = () => {
  page.value = 1; // 重置到第一页
  loadDishList();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadDishList();
};

const handleCurrentChange = (val) => {
  page.value = val;
  loadDishList();
};

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 新增菜品
const handleAdd = () => {
  form.id = null;
  form.name = '';
  form.categoryId = null;
  form.price = null;
  form.image = '';
  form.status = 1;
  form.flavors = [];
  dialogTitle.value = '新增菜品';
  dialogVisible.value = true;
};

// 编辑菜品
const handleEdit = async (row) => {
  try {
    const response = await getDishById(row.id);
    if (response.code === 200) {
      const dish = response.data;
      form.id = dish.id;
      form.name = dish.name;
      form.categoryId = dish.categoryId;
      form.price = dish.price;
      form.image = dish.image;
      form.status = dish.status;
      form.flavors = dish.flavors || [];
      dialogTitle.value = '编辑菜品';
      dialogVisible.value = true;
    }
  } catch (error) {
    console.error('获取菜品详情失败:', error);
    ElMessage.error('获取菜品详情失败');
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    let response;
    if (form.id) {
      response = await updateDish(form);
    } else {
      response = await addDish(form);
    }

    if (response.code === 200) {
      ElMessage.success(form.id ? '菜品更新成功' : '菜品新增成功');
      dialogVisible.value = false;
      loadDishList();
    } else {
      ElMessage.error(response.msg || (form.id ? '更新失败' : '新增失败'));
    }
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('提交失败:', error);
      ElMessage.error('操作失败，请重试');
    }
  }
};

// 单个删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜品吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteDish([id]);
    if (response.code === 200) {
      ElMessage.success('删除成功');
      loadDishList();
    } else {
      ElMessage.error(response.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除操作失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}个菜品吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteDish(selectedIds.value);
    if (response.code === 200) {
      ElMessage.success('批量删除成功');
      loadDishList();
    } else {
      ElMessage.error(response.msg || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除操作失败');
    }
  }
};

// 状态修改
const handleStatusChange = async (id, status) => {
  try {
    const response = await updateDishStatus(status, [id]);
    if (response.code === 200) {
      ElMessage.success(`菜品已${status === 1 ? '启售' : '停售'}`);
      loadDishList();
    } else {
      ElMessage.error(response.msg || '状态修改失败');
    }
  } catch (error) {
    console.error('状态修改失败:', error);
    ElMessage.error('状态修改操作失败');
  }
};

// 批量状态修改
const batchStatusText = ref('批量启售');
watch(selectedIds, (newVal) => {
  if (newVal.length > 0) {
    // 简单判断选中项的状态，取第一个的状态作为参考
    const firstStatus = dishList.value.find(item => item.id === newVal[0])?.status;
    batchStatusText.value = firstStatus === 1 ? '批量停售' : '批量启售';
  }
});

const handleBatchStatus = async () => {
  const targetStatus = batchStatusText.value === '批量启售' ? 1 : 0;
  try {
    const response = await updateDishStatus(targetStatus, selectedIds.value);
    if (response.code === 200) {
      ElMessage.success(`已${targetStatus === 1 ? '启售' : '停售'}选中菜品`);
      loadDishList();
    } else {
      ElMessage.error(response.msg || '批量状态修改失败');
    }
  } catch (error) {
    console.error('批量状态修改失败:', error);
    ElMessage.error('批量状态修改操作失败');
  }
};

// 图片上传成功处理
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    form.image = response.data; // 假设返回的data是图片URL
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败');
  }
};

// 添加口味
const addFlavor = () => {
  form.flavors.push({ name: '', value: '' });
};

// 格式化价格显示
const formatPrice = (row, column, value) => {
  return `¥${value.toFixed(2)}`;
};

// 页面初始化
onMounted(() => {
  loadCategoryList();
  loadDishList();
});
</script>

<style scoped>
.dish-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.flavor-item {
  margin: 10px 0;
  display: flex;
  align-items: center;
}
</style>